<template>
  <div ref="autocomplete">
    <el-autocomplete
      value-key="buttonCname"
      v-loading="loading"
      v-model="state"
      v-scrollLoad="selectLoadMore"
      :fetch-suggestions="querySearch"
      :placeholder="placeholder"
      :trigger-on-focus="false"
      @select="handleSelect"
    ></el-autocomplete>
  </div>
</template>

<script>
import { apiRequestPost } from '@/api/globalApi.js'

export default {
  name: 'InputLoadMore',
  props: {
    // 封装的查数据方法
    getOptionFn: {
      require: true,
    },
    // 后端定义的联想的key
    searchKey: {
      type: String,
      require: true,
    },
    // v-model的绑定值
    value: {
      type: String,
      require: true,
    },
    // placehoder
    placeholder: {
      type: String,
      default: '请输入',
    },
  },
  data() {
    return {
      state: '',
      loading: false,
      page: 1,
      pageTotal: 0,
    }
  },
  watch: {
    state(val) {
      this.$emit('input', val)
    },
    value(val) {
      this.state = val
    },
  },
  directives: {
    // 自定义指令，监听下拉框的滚动，滚动到底部就加载下一页
    scrollLoad: {
      bind(el, binding, vnode) {
        let wrapDom = el.querySelector('.el-autocomplete-suggestion__wrap')
        let listDom = el.querySelector('.el-autocomplete-suggestion__wrap  .el-autocomplete-suggestion__list')
        wrapDom.addEventListener(
          'scroll',
          (e) => {
            // 注意load的使用，节流
            let condition = wrapDom.offsetHeight + wrapDom.scrollTop + 10 - listDom.offsetHeight
            if (condition > 0 && !vnode.context.loading) {
              //滚动到底部则执行滚动方法load，binding.value就是v-scrollLoad绑定的值，加()表示执行绑定的方法
              binding.value()
            }
          },
          false
        )
      },
    },
  },
  methods: {
    async querySearch(queryString, cb) {
      console.log('-----------------00001')
      this.page = 1
      this.loading = true
      const query = {
        formEname: '',
        buttonEname: '',
        projectEname: '',
        moduleEname1: '',
        isAuth: '',
        current: 1,
        size: 10,
      }
      try {
        // let { result } = await this.getOptionFn({
        //   page: 1,
        //   pageSize: 50,
        //   [this.searchKey]: queryString,
        // })
        const response = await apiRequestPost('/rm2/buttonMaint/query', query)
        const newSuggestions = response.data.data.result
        // 根据实际情况修改下面的代码，展示数据
        if (newSuggestions) {
          let arr = []
          newSuggestions.forEach((item) => {
            arr.push(item)
          })
          cb(arr)
          // this.$nextTick(() => {
          //   setTimeout(() => {
          //     console.log('---------11133', this.$refs.autocomplete)
          //     const autocomplete = document.querySelector('.el-autocomplete-suggestion__wrap')
          //     autocomplete.addEventListener('scroll', this.scrollHandler)
          //   }, 0)
          // })
        } else {
          cb([])
        }
        this.pageTotal = response.data.data.total || 0
      } catch (e) {
        // console.log(e)
      } finally {
        this.loading = false
      }
    },
    handleSelect(item) {},
    // 加载更多
    async selectLoadMore() {
      console.log('----------000000089')
      if (Number(this.pageTotal) <= this.$refs['autocomplete'].$data.suggestions.length) {
        return
      }
      this.page = this.page + 1
      this.loading = true
      try {
        // let { result } = await this.getOptionFn({
        //   page: this.page,
        //   pageSize: 50,
        //   [this.searchKey]: this.state,
        // })
        const query = {
          formEname: '',
          buttonEname: '',
          projectEname: '',
          moduleEname1: '',
          isAuth: '',
          current: 1,
          size: 10,
        }
        const response = await apiRequestPost('/rm2/buttonMaint/query', query)
        const newSuggestions = response.data.data.result
        // 根据实际情况修改下面的代码，展示数据
        if (newSuggestions) {
          const arr = newSuggestions.map((item) => {
            return { item }
          })
          // 将数据添加到下拉列表
          this.$refs['autocomplete'].$data.suggestions = this.$refs['autocomplete'].$data.suggestions.concat(arr)
        }
        this.pageTotal = response.data.data.total || 0
      } catch (e) {
        // console.log(e)
      } finally {
        this.loading = false
      }
    },
    scrollHandler(e) {
      console.log('-------------000')
      const { scrollTop, scrollHeight, clientHeight } = e.target
      if (scrollTop + clientHeight >= scrollHeight - 10) {
        this.selectLoadMore()
      }
    },
  },
  mounted() {
    const autocomplete = document.querySelector('.el-autocomplete-suggestion__wrap')
    autocomplete.addEventListener('scroll', this.scrollHandler)
  },
  beforeUnmount() {
    const autocomplete = this.$refs.autocomplete.$el.querySelector('.el-autocomplete-suggestion__wrap')
    autocomplete.removeEventListener('scroll', this.scrollHandler)
  },
}
</script>
